package com.heima.wemedia.service.impl;

import com.heima.apis.schedule.ITaskClient;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private ITaskClient iTaskClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 发布延迟任务
     * @param wmNews
     */
    public void saveTask(WmNews wmNews) {
        // 创建task对象
        Task task = new Task();
        // 封装数据
        task.setExecuteTime(wmNews.getPublishTime().getTime()); // 发布时间
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType()); // 文章类型
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority()); // 任务优先级
        WmNews news = new WmNews();
        news.setId(wmNews.getId());
        // 将对象转化为字节数组
        byte[] serialize = ProtostuffUtil.serialize(news);
        task.setParameters(serialize);
        // 发起feign远程调用，添加延迟任务
        iTaskClient.addTask(task);
    }

    /**
     * 定时拉取已经到期的任务
     */
    @Scheduled(fixedDelay = 1000)
    public void pollTask(){
        Task task = iTaskClient.pollTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (task!= null) {
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
    }
}
